package com.magold.game.level;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.magold.time.AccurateTime;

public class RecordHandle {
	private static final int DEFAULT_TIME = 1*60*60*1000 - 1;	// 59:59:999
	private static final String RECORD_NAME = "record";
	private static final String KEY_MIN_TIME = "min_time";
	private static final String KEY_MAX_COIN_RATE = "max_coin";
	private final String mTimeKey;
	private final String mRateKey;
	private Context mGloableContext;
	
	public RecordHandle(String pLevelPath, Context pContext) {
		mTimeKey = pLevelPath + "_" + KEY_MIN_TIME;
		mRateKey = pLevelPath + "_" + KEY_MAX_COIN_RATE;
		mGloableContext = pContext;
	}
	
	public AccurateTime getMinTime() {
		SharedPreferences pref = pref();
		int ms = pref.getInt(mTimeKey, DEFAULT_TIME);
		return new AccurateTime(ms);
	}
	
	public float getMaxCoinRate() {
		SharedPreferences pref = pref();
		return pref.getFloat(mRateKey, 0);
	}

	public RecordUpdateResult update(AccurateTime pNewTime, float pNewCoinRate) {
		SharedPreferences.Editor editor = null;
		RecordUpdateResult result = RecordUpdateResult.NO_CHANGE;
		
		AccurateTime currTime = getMinTime();
		if (currTime.isLonger(pNewTime)) {
			result = RecordUpdateResult.UPDATE_TIME;
			editor = edit();
			editor.putInt(mTimeKey, (int) pNewTime.parseMilliseconds());
		}

		float currRate = getMaxCoinRate();
		if (currRate < pNewCoinRate) {
			result = RecordUpdateResult.combine(result, RecordUpdateResult.UPDATE_COIN);
			if (editor == null) editor = edit();
			editor.putFloat(mRateKey, pNewCoinRate);
		}
		
		if (editor != null) editor.apply();
		
		return result;
	}

	private SharedPreferences pref() {
		return mGloableContext.getSharedPreferences(RECORD_NAME, Context.MODE_WORLD_READABLE);
	}

	private Editor edit() {
		return pref().edit();
	}
	
}
